package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.controller.utils.BASE64Utils;
import com.ygqh.baby.model.YgSkuInfo;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgPromotion;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgPromotionService;
import com.ygqh.baby.service.YgSkuService;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.JsonUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

import static com.ygqh.baby.constant.RedisConstant.SKU_INFO;
import static com.ygqh.baby.constant.RedisConstant.SKU_KEY;

/**
 * @author admin
 */
@Controller
@RequestMapping("/admin/promotion")
public class PromotionController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private YgPromotionService ygPromotionService;
	@Autowired
	private YgProductService ygProductService;
	@Autowired
	private YgSkuService ygSkuService;
	@Autowired
	private RedisDao redisDao;

	@RequestMapping("searchPromotion")
	@ResponseBody
	public Map<String, Object> searchPromotion(String q, QueryInfo queryInfo, Date startDate, Date endDate,
											   PromotionStatus pStatus, PromotionType pType) {

		ResultSet<YgPromotion> resultSet = ygPromotionService.search(queryInfo, getSession().getSupplierId(), pStatus,
				pType, startDate, endDate, q);

		return resultSet.toDatatables(null);
	}

	@RequestMapping("addPromotion")
	@ResponseBody
	public Message addPromotion(String promotion) {
		YgPromotion p = JsonUtils.toObject(promotion, YgPromotion.class);
		return ygPromotionService.addPromotion(getSession().getSupplierId(), p.getPromotionTitle(),
				p.getPromotionType(), p.getLimitPrice(), p.getDiscountPrice(), p.getProductIds(), p.getUseCoupon(),
				p.getRemark(), p.getStartDate(), p.getEndDate(), getSession().getTrueName(),p.getPlatformNo());

	}

	@RequestMapping("updatePromotion")
	@ResponseBody
	public Message updatePromotion(String promotion) {
		YgPromotion p = JsonUtils.toObject(promotion, YgPromotion.class);
		ygPromotionService.updatePromotion(p.getId(), p.getPromotionTitle(), p.getPromotionType(), p.getLimitPrice(),
				p.getDiscountPrice(), p.getProductIds(), p.getUseCoupon(), p.getRemark(), p.getStartDate(),
				p.getEndDate(), getSession().getTrueName(),p.getPlatformNo());

		return SUCCESS_MESSAGE;
	}

	@RequestMapping("getPromotion")
	@ResponseBody
	public YgPromotion getPromotion(Long id) {
		return ygPromotionService.findById(id);
	}

	@RequestMapping("getProductListByPromotionId")
	@ResponseBody
	public Map<String, Object> getProductListByPromotionId(Long promotionId) {
		QueryInfo queryInfo = new QueryInfo();
		queryInfo.setEnd(200);
		List<YgProduct> list = ygProductService.findProductByPromotionId(queryInfo, promotionId);
		ResultSet<YgProduct> result = new ResultSet<>(1, list);
		return result.toDatatables(null);
	}

	@RequestMapping(value = "setExpress")
	@ResponseBody
	public Message setExpress(@RequestParam BigDecimal limitPrice, @RequestParam BigDecimal exprice,
							  @RequestParam SalesPlatform salesPlatform) {
		Map<String, BigDecimal> map = new HashMap<>();
		map.put("price", exprice);
		map.put("limitPrice", limitPrice);
		String key = String.format(RedisConstant.EXPRESS_KEY, salesPlatform);
		String string = redisDao.set(key, JSONObject.toJSONString(map), 0);
		return Message.success(string);
	}


	@RequestMapping(value = "getExpress")
	@ResponseBody
	public Message getExpress() {
		String key = String.format(RedisConstant.EXPRESS_KEY, SalesPlatform.Yiigoo.name());
		Map<String, String> map = new HashMap<String, String>();
		map.put(SalesPlatform.Yiigoo.name(), redisDao.get(key));
		key = String.format(RedisConstant.EXPRESS_KEY, SalesPlatform.Yijiadian.name());
		map.put(SalesPlatform.Yijiadian.name(), redisDao.get(key));
		return Message.success(map);
	}

	@RequestMapping(value = "setWeixinReply")
	@ResponseBody
	public Message setWeixinReply(String k, String v) throws Exception {
		String baseStr = BASE64Utils.encryptBASE64(k.getBytes());
		String string = redisDao.set(RedisConstant.WEIXIN_KEY + baseStr, v, 0);
		return Message.success(string);
	}

	@RequestMapping(value = "getWeixinReply")
	@ResponseBody
	public Message getWeixinReply(String k) throws Exception {
		String baseStr = BASE64Utils.encryptBASE64(k.getBytes());
		String string = redisDao.get(RedisConstant.WEIXIN_KEY + baseStr);
		return Message.success(string);
	}

	@RequestMapping(value = "getWeixinValues")
	@ResponseBody
	public Message getWeixinValues() {
		List<String> values = new ArrayList<>();
		// 获取微信key
		Set<byte[]> weixinkeys = redisDao.keys(RedisConstant.WEIXIN_KEY);
		for (byte[] weixinkey : weixinkeys) {
			values.add(new String(weixinkey));
		}
		return Message.success(values);
	}

	@SuppressWarnings({"unchecked"})
	@RequestMapping("getVipPrice")
	@ResponseBody
	public Message getVipPrice() {
		String str = redisDao.get(RedisConstant.VIP_KEY);
		Map<String, BigDecimal> map = JSONObject.parseObject(str, Map.class);
		return Message.success(map);
	}

	@RequestMapping(value = "setVipPrice")
	@ResponseBody
	public Message setVipPrice(@RequestParam BigDecimal sourceVipPrice, @RequestParam BigDecimal vipPrice) {
		Map<String, BigDecimal> map = new HashMap<>();
		map.put("sourceVipPrice", sourceVipPrice);
		map.put("vipPrice", vipPrice);
		String string = redisDao.set(RedisConstant.VIP_KEY, JSONObject.toJSONString(map), 0);
		return Message.success(string);
	}

	@RequestMapping(value = "setSku")
	@ResponseBody
	public Message setSku(String ids) {
		List<String> productIds = java.util.Arrays.asList(ids.split(","));

		List<YgSkuInfo> list = ygSkuService.getSkuInfoList(productIds);
		List<Long> skuIds = new ArrayList<>();
		if (list == null) {
			return Message.error("产品ID错误");

		} else {
			for (YgSkuInfo sku : list) {
				skuIds.add(sku.getSkuId());
			}
		}
		String string = redisDao.set(SKU_INFO, JSONObject.toJSONString(list), 0);
		// 设置SKUID
		redisDao.set(SKU_KEY, JSONObject.toJSONString(skuIds.toString()), 0);
		return Message.success(string);
	}

	@RequestMapping(value = "getProduct")
	@ResponseBody
	public Message getProduct() {

		String string = redisDao.get(SKU_INFO);
		List<YgSkuInfo> list = JSON.parseObject(string, new TypeReference<List<YgSkuInfo>>() {
		});
		List<Long> productIds = new ArrayList<>();

		if (list != null) {
			for (YgSkuInfo sku : list) {
				productIds.add(sku.getProductId());
			}

		}
		return Message.success(productIds.toString());
	}

	@RequestMapping(value = "setCoupon")
	@ResponseBody
	public Message setCoupon(Long[] ids, Long quantity) {
		Map<String, String> map = new HashMap<>();
		map.put("couponBatchIds", StringUtils.join(ids, ","));
		map.put("quantity", quantity.toString());
		String string = redisDao.set(RedisConstant.COUPON_KEY, JSONObject.toJSONString(map), 0);
		return Message.success(string);
	}

	@RequestMapping(value = "getCoupon")
	@ResponseBody
	public Message setCoupon() {
		String couponInfo = redisDao.get(RedisConstant.COUPON_KEY);
		Map map = JSON.parseObject(couponInfo, Map.class);
		return Message.success(map);
	}

	@RequestMapping("createManZeng")
	@ResponseBody
	public Message createManZeng(String productCode) {
		AdminUser user = SessionUtil.getCurrentUser();
		String string = ygPromotionService.addPromotionProduct(PromotionType.ManZeng, productCode, user.getTrueName());
		return Message.success(string);
	}

	@RequestMapping("getGiveMember")
	@ResponseBody
	public Message getGiveMember() {
		String str = redisDao.get("ToMemberNotPay");
		return Message.success(str);
	}

	@RequestMapping("setGiveMember")
	@ResponseBody
	public Message setGiveMember(String userNames) {
		String str = redisDao.set("ToMemberNotPay", userNames, 0);
		return Message.success(str);
	}

	@RequestMapping("setDisableCoupon")
	@ResponseBody
	public Message setDisableCoupon(String startDate, String endDate) {
		Map<String, String> map = new HashMap<>();
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		String result = redisDao.set(RedisConstant.DISABLE_COUPON_KEY, JSONObject.toJSONString(map), 0);
		return Message.success(result);
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("getDisableCoupon")
	@ResponseBody
	public Message getDisableCoupon() {
		String couponInfo = redisDao.get(RedisConstant.DISABLE_COUPON_KEY);
		Map map = JSON.parseObject(couponInfo, Map.class);
		return Message.success(map);
	}

	@RequestMapping("setManFanCoupon")
	@ResponseBody
	public Message setManFanCoupon(BigDecimal limitPrice, String couponBatchIds) {
		ygPromotionService.setManFanCoupon(limitPrice, couponBatchIds);
		return Message.success(null);
	}

	@RequestMapping("getManFanCoupon")
	@ResponseBody
	public Message getManFanCoupon() {
		return Message.success(ygPromotionService.getManFanCoupon());
	}

	@RequestMapping("delManFanCoupon")
	@ResponseBody
	public Message delManFanCoupon() {
		ygPromotionService.delManFanCoupon();
		return Message.success(null);
	}

	/**
	 * 成为代理条件
	 *
	 * @param recommendCount 粉丝数
	 * @param orderCount     下单数
	 * @param salesPlatform  平台
	 * @return
	 */
	@RequestMapping("setUserAgentCondition")
	@ResponseBody
	public Message setUserAgentCondition(@RequestParam Long recommendCount, @RequestParam Long orderCount,
										 @RequestParam SalesPlatform salesPlatform) {
		String key = String.format(RedisConstant.USER_AGENT_CONDITION_PREFIX_KEY, salesPlatform);
		Map<String, Object> data = new HashMap<>(2);
		data.put("recommendCount", recommendCount);
		data.put("orderCount", orderCount);
		redisDao.set(key, JSON.toJSONString(data), 0);
		return Message.success(null);
	}

	@RequestMapping("getUserAgentCondition")
	@ResponseBody
	public Message setUserAgentCondition(@RequestParam SalesPlatform salesPlatform) {
		String key = String.format(RedisConstant.USER_AGENT_CONDITION_PREFIX_KEY, salesPlatform);
		String result = redisDao.get(key);
		return Message.success(JSON.parseObject(result, Map.class));
	}

	/**
	 * 设置首页的tab 标签内容
	 *
	 * @param tablist       tab标签列表
	 * @param salesPlatform 平台
	 * @return
	 */
	@RequestMapping("setHomeTab")
	@ResponseBody
	public Message setHomeTab(String tablist, SalesPlatform salesPlatform) {
		tablist = tablist.replace("，", ",");
		String key = String.format(RedisConstant.MALL_INDEX_TAB_KEY, salesPlatform.name());
		redisDao.set(key, tablist, 0);
		return Message.success(null);
	}

	/**
	 * 获取首页的tab 标签内容
	 *
	 * @return
	 */
	@RequestMapping("getHomeTab")
	@ResponseBody
	public Message getHomeTab() {
		String key = String.format(RedisConstant.MALL_INDEX_TAB_KEY, SalesPlatform.Yiigoo.name());
		Map<String, String> map = new HashMap<String, String>(2);
		map.put(SalesPlatform.Yiigoo.name(), redisDao.get(key));
		key = String.format(RedisConstant.MALL_INDEX_TAB_KEY, SalesPlatform.Yijiadian.name());
		map.put(SalesPlatform.Yijiadian.name(), redisDao.get(key));
		return Message.success(map);
	}

	/**
	 * 设置新客优惠价
	 *
	 * @param price         优惠价
	 * @param salesPlatform 平台
	 * @return
	 */
	@RequestMapping("setNewCustomCoupon")
	@ResponseBody
	public Message setNewCustomCoupon(BigDecimal price, SalesPlatform salesPlatform) {
		String key = String.format(RedisConstant.NEW_CUSTOM_COUPON_PRICE_PREFIX_KEY, salesPlatform);
		redisDao.set(key, price.toString(), 0);
		return Message.success(null);
	}

	/**
	 * 新客优惠价
	 *
	 * @return
	 */
	@RequestMapping("getNewCustomCoupon")
	@ResponseBody
	public Message getNewCustomCoupon() {
		Map<String, Object> data = new HashMap<>(2);
		String key = String.format(RedisConstant.NEW_CUSTOM_COUPON_PRICE_PREFIX_KEY, SalesPlatform.Yiigoo);
		data.put(SalesPlatform.Yiigoo.name(), redisDao.get(key));
		key = String.format(RedisConstant.NEW_CUSTOM_COUPON_PRICE_PREFIX_KEY, SalesPlatform.Yijiadian);
		data.put(SalesPlatform.Yijiadian.name(), redisDao.get(key));
		return Message.success(data);
	}

	/**
	 * 代理支付成功送券设置
	 *
	 * @param couponIds
	 * @return
	 */
	@RequestMapping("setUserAgentPaySuccessCoupon")
	@ResponseBody
	public Message setUserAgentPaySuccessCoupon(String couponIds) {
		String result = redisDao.set(RedisConstant.USERAGENT_PAYSUCCESS_COUPON, couponIds, 0);
		return Message.success(result);
	}

	@RequestMapping("getUserAgentPaySuccessCoupon")
	@ResponseBody
	public Message getUserAgentPaySuccessCoupon() {
		return Message.success(redisDao.get(RedisConstant.USERAGENT_PAYSUCCESS_COUPON));
	}
}
